package com.andy.rpc.handler;

import com.andy.rpc.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class ServerHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;
        System.out.println("rpcRequest====>>>> "+rpcRequest);

        //拿到spring管理的对象
        Class<?> targetClass = Class.forName(rpcRequest.getClassName());
        Object bean = applicationContext.getBean(targetClass);

        //拿到要调用的方法
        Method method = targetClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());

        //反射调用方法，并拿到出参
        Object result = method.invoke(bean, rpcRequest.getParameters());

        //将出参写入通道，并推送给客户端
        ctx.writeAndFlush(result);
    }
}
